package com.androidframelearn.http_okio;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    private Button btn_post_keyvalue;

    private Button btn_post_string;


    private Button btn_post_file;

    private Button btn_post_form;

    private static final String TAG = "MainActivity";

    private static final String URL = "http://10.0.2.2:8080/androidframelearn/";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化UI
        initUI();

        // 1.POST请求提交键值对
        postKeyValue();
        // 2.POST请求提交字符串
        postString();
        // 3.POST请求提交文件
        postFile();
        // 4.POST请求提交表单
        postForm();
    }

    /**
     * 初始化UI
     */
    private void initUI() {
        btn_post_keyvalue = findViewById(R.id.btn_post_keyvalue);
        btn_post_string = findViewById(R.id.btn_post_string);
        btn_post_file = findViewById(R.id.btn_post_file);
        btn_post_form = findViewById(R.id.btn_post_form);
    }

    /**
     * POST请求提交键值对
     */
    private void postKeyValue() {
        btn_post_keyvalue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 1.构建Client对象
                OkHttpClient client = new OkHttpClient();
                // 2.采用建造者模式和链式调用构建键值对对象
                FormBody formBody = new FormBody.Builder()
                        .add("username", "admin")
                        .add("password", "123456")
                        .build();
                // 3.采用建造者模式和链式调用构建Request对象
                final Request request = new Request.Builder()
                        .url(URL) // 请求URL
                        .post(formBody) // 默认就是get请求，可以不写
                        .build();
                // 4.通过1和3产生的Client和Request对象生成Call对象
                Call call = client.newCall(request);
                // 5.调用Call对象的enqueue()方法，并且实现一个回调实现类
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(@NotNull Call call, @NotNull IOException e) {
                        Log.d(TAG, "发送post请求键值对失败！");
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                        Log.d(TAG, "发送post请求键值对成功！请求到的信息为：" + response.body().string());
                    }
                });
            }
        });
    }

    /**
     * POST请求提交字符串
     */
    private void postString() {
        btn_post_string.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 1.构建Client对象
                OkHttpClient client = new OkHttpClient();
                // 2.构造RequestBody
                RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain;charset=utf-8"), "{username:admin;password:123456}");
                // 3.采用建造者模式和链式调用构建Request对象
                final Request request = new Request.Builder()
                        .url(URL) // 请求URL
                        .post(requestBody) // 默认就是get请求，可以不写
                        .build();
                // 4.通过1和3产生的Client和Request对象生成Call对象
                Call call = client.newCall(request);
                // 5.调用Call对象的enqueue()方法，并且实现一个回调实现类
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(@NotNull Call call, @NotNull IOException e) {
                        Log.d(TAG, "发送post请求字符串失败！");
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                        Log.d(TAG, "发送post请求字符串成功！请求到的信息为：" + response.body().string());
                    }
                });
            }
        });

    }

    /**
     * POST请求提交文件
     */
    private void postFile() {
        btn_post_file.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 1.构建Client对象
                OkHttpClient client = new OkHttpClient();
                // 2.构造RequestBody
                // 2.1 构造文件对象
                File file = new File(MainActivity.this.getExternalFilesDir(null), "test.txt");
                Log.i(TAG,Environment.getExternalStorageDirectory().toString());
                // 2.2 判断文件是否为空
                if (!file.exists()){
                    Log.i(TAG,"文件为空，无法创建");
                }else{
                    // 2.3 通过文件构造构造RequestBody对象
                    RequestBody requestBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
                    // 3.采用建造者模式和链式调用构建Request对象
                    final Request request = new Request.Builder()
                            .url(URL) // 请求URL
                            .post(requestBody) // 默认就是get请求，可以不写
                            .build();
                    // 4.通过1和3产生的Client和Request对象生成Call对象
                    Call call = client.newCall(request);
                    // 5.调用Call对象的enqueue()方法，并且实现一个回调实现类
                    call.enqueue(new Callback() {
                        @Override
                        public void onFailure(@NotNull Call call, @NotNull IOException e) {
                            Log.d(TAG, "发送post请求文件失败！");
                            e.printStackTrace();
                        }

                        @Override
                        public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                            Log.d(TAG, "发送post请求文件成功！请求到的信息为：" + response.body().string());
                        }
                    });
                }
            }
        });
    }

    /**
     * POST请求提交表单
     */
    private void postForm() {
        btn_post_form.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 1.构建Client对象
                OkHttpClient client = new OkHttpClient();
                // 2.构造RequestBody
                // 2.1 构造文件对象
                File file = new File(MainActivity.this.getExternalFilesDir(null), "test.png");
                Log.i(TAG,Environment.getExternalStorageDirectory().toString());
                // 2.2 判断文件是否为空
                if (!file.exists()){
                    Log.i(TAG,"文件为空，无法创建");
                }else{
                    // 2.3 通过表单构造构造RequestBody对象
                    RequestBody muiltipartBody = new MultipartBody.Builder()
                            //一定要设置这句
                            .setType(MultipartBody.FORM)
                            .addFormDataPart("username", "admin")//
                            .addFormDataPart("password", "admin")//
                            .addFormDataPart("myfile", "test.png", RequestBody.create(MediaType.parse("application/octet-stream"), file))
                            .build();
                    // 3.采用建造者模式和链式调用构建Request对象
                    final Request request = new Request.Builder()
                            .url(URL) // 请求URL
                            .post(muiltipartBody) // 默认就是get请求，可以不写
                            .build();
                    // 4.通过1和3产生的Client和Request对象生成Call对象
                    Call call = client.newCall(request);
                    // 5.调用Call对象的enqueue()方法，并且实现一个回调实现类
                    call.enqueue(new Callback() {
                        @Override
                        public void onFailure(@NotNull Call call, @NotNull IOException e) {
                            Log.d(TAG, "发送post请求表单失败！");
                            e.printStackTrace();
                        }

                        @Override
                        public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                            Log.d(TAG, "发送post请求表单成功！请求到的信息为：" + response.body().string());
                        }
                    });
                }
            }
        });
    }

}
